﻿using MetaView.Client.Views;
using MetaView.Main.Views;
using Microsoft.Extensions.Hosting;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Wpf.Ui;

namespace MetaView.Main.Services
{
    /// <summary>
    /// 应用程序的托管主机
    /// </summary>
    public class ApplicationHostService : IHostedService
    {
        private readonly IServiceProvider _serviceProvider;
        private INavigationWindow _navigationWindow;

        public ApplicationHostService(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        /// <summary>
        /// 当应用程序主机准备启动服务时触发
        /// </summary>
        /// <param name="cancellationToken">表示启动过程已中止</param>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            await HandleActivationAsync();
        }

        /// <summary>
        /// 当应用程序主机执行正常关机时触发
        /// </summary>
        /// <param name="cancellationToken">表示关机过程不应再正常</param>
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await Task.CompletedTask;
        }

        /// <summary>
        /// 在激活期间创建主窗口
        /// </summary>
        private async Task HandleActivationAsync()
        {
            await Task.CompletedTask;

            if (!Application.Current.Windows.OfType<MainWindow>().Any())
            {
                var windowInstance = _serviceProvider.GetService(typeof(INavigationWindow));
                _navigationWindow = windowInstance as INavigationWindow;
                if (_navigationWindow != null)
                {
                    _navigationWindow.ShowWindow();
                    _navigationWindow.Navigate(typeof(Views.Pages.DashboardPage));
                }
                else
                {
                    // 异常处理：服务未注册时的备选方案 
                    var fallbackWindow = new Window();
                    fallbackWindow.Show();
                }
            }

            await Task.CompletedTask;
        }
    }
}
